package next.SupportFunctionality;

import com.google.android.maps.MapActivity;
import com.google.android.maps.Overlay;

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import com.google.android.maps.MapView;

//--Import for method of the MapController class
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.maps.MapController;

//--Geopoints
import com.google.android.maps.GeoPoint;

//--Add Markers
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;

//--java imports
import java.io.IOException;
import java.util.List;
import java.util.Locale;

import next.CustomLayout.TitleWidget;
import next.TemplateActivity.NormalActivity;
import next.TemplateActivity.R;
import next.control.ApplicationController;

//--My Location
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

public class MapsFunctionality extends MapActivity {

	// --Variables--
	protected String tag = new String("Events");
	protected MapView mapView;
	protected MapController mc;
	protected GeoPoint Lastp,p, aux;
	protected String locationHome[] = { "4.627137", "-74.063237" };

	protected LocationManager lm;
	protected LocationListener locationListener;
	protected Location lastLocation;

	protected Button GO, AddMARKER, SAVE;
	protected EditText ete;

	/** --Class for overlay */
	class MapOverlay extends com.google.android.maps.Overlay {

		// --This method call the draw method for the maps--
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			super.draw(canvas, mapView, shadow);

			for (int i = 0; i < ApplicationController.markers.size(); i += 2) {
				double lat = Double.parseDouble(ApplicationController.markers.get(i));
				double lng = Double.parseDouble(ApplicationController.markers.get(i+1));
				aux = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
				// ---translate the GeoPoint to screen pixels---
				Point screenPts = new Point();
				mapView.getProjection().toPixels(aux, screenPts);
				// ---add the marker---
				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.pushpin);
				canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
			}
			return true;
		}

		// --This method overwrite the touch event over the map--
		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) {
			// ---when user lifts his finger---
			if (event.getAction() == 1) {
				Lastp = mapView.getProjection().fromPixels(
						(int) event.getX(), (int) event.getY());

				Toast.makeText(
						getBaseContext(),
						"Location: " + p.getLatitudeE6() / 1E6 + ","
								+ p.getLongitudeE6() / 1E6, Toast.LENGTH_SHORT)
						.show();

				// --According the point you touch it will return the Address
				// name
				/*
				 * Geocoder geoCoder = new
				 * Geocoder(getApplicationContext(),Locale.getDefault()); try {
				 * List<Address> addresses = geoCoder.getFromLocation(
				 * p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1); String
				 * add = ""; if (addresses!=null) { if (addresses.size() > 0){
				 * for (int i = 0; i <
				 * addresses.get(0).getMaxAddressLineIndex(); i++) add +=
				 * addresses.get(0).getAddressLine(i) + "\n"; } }
				 * Toast.makeText(getBaseContext(),
				 * add,Toast.LENGTH_SHORT).show(); } catch (IOException e) {
				 * e.printStackTrace(); } return true;
				 */

			}
			return false;
		}
	}

	/** --Class for Update Location */
	private class MyLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location loc) {
			if (loc != null) {
				Toast.makeText(
						getBaseContext(),
						"Location changed : Lat: " + loc.getLatitude()
								+ " Lng: " + loc.getLongitude(),
						Toast.LENGTH_SHORT).show();

				p = new GeoPoint((int) (loc.getLatitude() * 1E6),
						(int) (loc.getLongitude() * 1E6));
				mc.animateTo(p);
				mc.setZoom(18);
				lastLocation = loc;
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.support_map_custom_mv);
		
		//--Initialize title Widget
        TitleWidget titleWidget = (TitleWidget)findViewById(R.id.normal_activity_CV_TWI1);
        //--Call the methods to change the underlying widgets
        titleWidget.setTitle("S-3R4_MAP");
        titleWidget.setIcon(R.drawable.ic_launcher_admin_si);
        titleWidget.showProgressBar();
        titleWidget.hideProgressBar();
        
		// --Displaying the zoom control
		mapView = (MapView) findViewById(R.id.mapView);
		mapView.setBuiltInZoomControls(true);
		mapView.setSatellite(true);
		
		// --Assembling Widgets
		ete=(EditText)findViewById(R.id.support_map_custom_mvET1);
		ete.setOnTouchListener(NormalActivity.VoiceListener);
		GO = (Button)findViewById(R.id.support_map_custom_mvBN1);
		AddMARKER =(Button)findViewById(R.id.support_map_custom_mvBN2);
		SAVE =(Button)findViewById(R.id.support_map_custom_mvBN3);

		GO.setOnClickListener(MapListener);
		AddMARKER.setOnClickListener(MapListener);
		SAVE.setOnClickListener(MapListener);

		// -- Getting my current location
		GetMyLocation();

		// --Going to a Point
		/*
		 * String coordinates[] = { "1.352566007", "103.78921587" };
		 * GoToPoint(coordinates);
		 */

		// --Going to an Address

		/*
		 * try { GoToAddress("empire state building"); } catch (IOException e) {
		 * // TODO Auto-generated catch block e.printStackTrace(); }
		 */

		// ---Add a location marker---
		
		 MapOverlay mapOverlay = new MapOverlay(); List<Overlay>
		 listOfOverlays = mapView.getOverlays(); listOfOverlays.clear();
		 listOfOverlays.add(mapOverlay);
		
	}

	/** Tracing routes in the map */
	@Override
	public boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	/** Go to a single point in the map */
	public void GoToPoint(String coordinates[]) {
		mc = mapView.getController();
		double lat = Double.parseDouble(coordinates[0]);
		double lng = Double.parseDouble(coordinates[1]);
		p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
		mc.animateTo(p);
		mc.setZoom(18);
		mapView.invalidate();
	}

	/** Go to an address in the map */
	public void GoToAddress(String address) throws IOException {
		// ---geo-coding---
		Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
		List<Address> addresses = geoCoder.getFromLocationName(address, 1);

		if (addresses.size() > 0) {
			p = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6),
					(int) (addresses.get(0).getLongitude() * 1E6));
			mc = mapView.getController();
			mc.animateTo(p);
			mapView.invalidate();
		}
	}

	/** Getting my location and updating my movements */
	public void GetMyLocation() {

		String provider = LocationManager.GPS_PROVIDER;
		// String provider = LocationManager.NETWORK_PROVIDER;

		// --My current
		// Location--------------------------------------------------------------------
		// Location location = lm.getLastKnownLocation(provider);

		// ---use the LocationManager class to obtain locations data---
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationListener = new MyLocationListener();
		// --looking for a provider
		List<String> providers = lm.getProviders(true);
		int cualProvider = -1;

		// --Loop over the array backwards, and if you get an accurate location,
		// then break out the loop
		for (int i = providers.size() - 1; i >= 0; i--) {

			// if (lm.isProviderEnabled(providers.get(i))){
			if (provider.equals((providers.get(i)))) {
				cualProvider = i;
				break;
			}
		}

		if (cualProvider != -1) {

			// --LocationUpdates: Provider, minTime(millisecond),
			// minDistance(meter), Listener
			lm.requestLocationUpdates(providers.get(cualProvider), 0, 0,
					locationListener);
			lastLocation = lm.getLastKnownLocation(providers.get(cualProvider));

			if (lastLocation != null) {
				String[] coordinates = new String[2];
				coordinates[0] = "" + lastLocation.getLatitude();
				coordinates[1] = "" + lastLocation.getLongitude();
				Toast.makeText(getBaseContext(), "Initial Location",
						Toast.LENGTH_SHORT).show();
				GoToPoint(coordinates);
			} else {
				// --You are in home. In this case Javeriana
				this.GoToPoint(locationHome);
				Toast.makeText(getBaseContext(), "Location Home",
						Toast.LENGTH_SHORT).show();
			}

		} else {
			Toast.makeText(getBaseContext(), "No current provider",
					Toast.LENGTH_SHORT).show();

		}
	}

	/**Includes new markers and enable to go places from addresses*/
	private OnClickListener MapListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
		if (v.getId()==GO.getId()){
			try { GoToAddress(ete.getText().toString()); } catch (IOException e)
			{ Log.d("Exception", "MapException");}
		}
		else if (v.getId()==AddMARKER.getId()){
			if (Lastp!=null)
			{
				ApplicationController.markers.add(Lastp.getLatitudeE6()/1E6+"");
				ApplicationController.markers.add(Lastp.getLongitudeE6()/1E6+"");
				mapView.invalidate();
			}
		}
		else if (v.getId()==SAVE.getId()){
			
		}
			
		}
	};
	
		// --Cycle life of
		// App-------------------------------------------------------
		/** Called when the activity start. */
		@Override
		public void onStart() {
			super.onStart();
			
			Log.d(tag, "In the onStart() event");
		}

		/** Called because of activity was STOPPED, and is now in foreground. */
		@Override
		public void onRestart() {
			Log.d(tag, "In the onRestart() event");
		}

		/** Called because of activity was PAUSED, and is now in foreground. */
		@Override
		public void onResume() {
			super.onResume();
			//--Verify if the profile button was clicked
		 	super.onRestart();
		 	if (ApplicationController.GOPROFILE){
		 		//--close the last Activity
		 		finish();
		 	}		
		 		else{ ApplicationController.GOPROFILE=false;
		 		}
		 			 	
		 	//--Managing EditText with voice
		 	if (ApplicationController.EditTextVoice!=-1 && 
		 			!(ApplicationController.filterWord.equalsIgnoreCase("")) )
		 	{
		 		EditText et=(EditText) findViewById(ApplicationController.EditTextVoice);
		 		et.setText(ApplicationController.filterWord);
		 		ApplicationController.EditTextVoice=-1;
		 		ApplicationController.filterWord="";
		 	}
			Log.d(tag, "In the onResume() event");
		}

		/** Called when other activity comes in front. */
		@Override
		public void onPause() {
			super.onPause();
			Log.d(tag, "In the onPause() event");
		}

		/** Called when this activity is no longer visible. */
		@Override
		public void onStop() {
			super.onStop();
			Log.d(tag, "In the onStop() event");
		}

		@Override
		public void onDestroy() {
			super.onDestroy();
			ApplicationController.CLOSE();
     		Log.d(tag, "In the onDestroy() event");
		}
		//--END Cycle life of

}